package com.alogic.xscript.plugins;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;
import com.alogic.xscript.AbstractLogiclet;
import org.yaml.snakeyaml.Yaml;
import java.util.Map;

/**
 * 将当前文档内容转换为yaml，并存入到变量
 *
 * @since 1.6.12.27 [20190403 duanyy] <br>
 */
public class AsYaml extends AbstractLogiclet{
    protected String id;

    protected static ThreadLocal<Yaml> yamlLocal = new ThreadLocal<Yaml>(){
        protected Yaml initialValue() {
            return new Yaml();
        };
    };

    public AsYaml(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        id = PropertiesConstants.getString(p,"id","",true);
    }

    @Override
    protected void onExecute(Map<String, Object> root,
                             Map<String, Object> current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        if (StringUtils.isNotEmpty(id)){
            String content = yamlLocal.get().dump(current);
            if (StringUtils.isNotEmpty(content)){
                ctx.SetValue(id, content);
            }
        }
    }
}